package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysInviteMail;
import com.ruoyi.system.mapper.SysInviteMailMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.domain.MailVo;
import com.ruoyi.web.controller.domain.UserPasswordVo;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    private static final String EMAIL_PATTERN =
            "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private static Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysPostService postService;
    @Autowired
    private SysInviteMailMapper sysInviteMailMapper;

    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    public static boolean isValidEmailAddress(String email) {
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    /**
     * 获取用户列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
//    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }


    /**
     * 获取用户列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin')")
    @GetMapping("/userManagerList")
    public TableDataInfo userManagerList(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        List<SysUser> selects = new ArrayList<>();
        for (SysUser sysUser : list) {
            List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(sysUser.getUserId());
            if (userRoles != null && userRoles.size() >= 1) {
                long roleId = userRoles.get(0).getRoleId();
                if (roleId == Constants.ROLE_ID_ADMIN || roleId == Constants.ROLE_ID_COMMON) {
                    sysUser.setRoleId(roleId);
                    selects.add(sysUser);
                }
            }
//            SysUserRole sysUserRole = new SysUserRole();
//            sysUserRole.setUserId(sysUser.getUserId());
//            sysUserRoleMapper.s
//            List<Long> roleIds = roleMapper.selectRoleListByUserId(sysUser.getUserId());
//            if (roleIds != null) {
//                long roleId = roleIds.get(0);
//                if (sysUser.getRoleId() == Constants.ROLE_ID_ADMIN || sysUser.getRoleId() == Constants.ROLE_ID_COMMON) {
//
//                }
//
//            }
        }

        return getDataTable(selects);
    }

    /**
     * 发送邮件
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @GetMapping("/sendMail")
    public synchronized AjaxResult sendMail(MailVo mailVo) {
//        logger.info("sendMail： " + .toJSONString(mailVo));
        if (!isValidEmailAddress(mailVo.mail)) {
            return error("请输入正确的邮箱");
        }
        if (mailVo.nickname == null || mailVo.nickname.length() == 0 || mailVo.nickname.trim().length() != mailVo.nickname.length()) {
            return error("请输入正确的昵称");
        }
        if (!Constants.isValidRole(mailVo.role)) {
            return error("请输入正确的角色");
        }

        SysInviteMail sysInviteMail = new SysInviteMail();
        sysInviteMail.setMail(mailVo.mail);
        List<SysInviteMail> mailList = sysInviteMailMapper.selectSysInviteMailList(sysInviteMail);
        Date now = new Date();
        Date expiredDate = new Date(now.getTime() + 14 * 86400 * 1000);
        if (mailList.isEmpty()) {
            sysInviteMail.setName(mailVo.nickname);
            sysInviteMail.setRole(mailVo.role);
            sysInviteMail.setCreateTime(now);
            sysInviteMail.setExpiredTime(expiredDate);
            sysInviteMailMapper.insertSysInviteMail(sysInviteMail);
        } else {
            sysInviteMail = mailList.get(0);
            sysInviteMail.setName(mailVo.nickname);
            sysInviteMail.setRole(mailVo.role);
            sysInviteMail.setCreateTime(now);
            sysInviteMail.setExpiredTime(expiredDate);
            sysInviteMailMapper.updateSysInviteMail(sysInviteMail);
        }

        // 设置发件人信息
        String from = "cceshi907@gmail.com";
        String password = "lprn vwxl ebms lqqq";//"AYNGUXPJVDFPKAXZ";//"donald136816";

        // 设置收件人信息
        String to = sysInviteMail.getMail();//"vital_isbb@126.com";

        // 设置邮件服务器
        Properties props = new Properties();//System.getProperties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.auth", "true");
//        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.port", "587");
//        props.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });

        String mailTitle = "Test Email from Java";
        String mailText = "Hello, This is a test email sent from Java program.";

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(mailTitle);
            message.setText(mailText);
            Transport.send(message);
            System.out.println("Email sent successfully.");
            return success(true);
        } catch (MessagingException mex) {
            mex.printStackTrace();
            return error("发送失败");
        }
    }

    //    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @GetMapping("/modifyUser")
    public synchronized AjaxResult modifyUser(MailVo mailVo) {
        if (mailVo.nickname == null || mailVo.nickname.length() == 0 || mailVo.nickname.trim().length() != mailVo.nickname.length()) {
            return error("请输入正确的昵称");
        }
        if (!Constants.isValidRole(mailVo.role)) {
            return error("请输入正确的角色");
        }

        if (!isRoleAdmin()) {
            return error("权限不足");
        }

        SysUser sysUser = new SysUser();
        sysUser.setUserName(mailVo.getMail());
        List<SysUser> userList = userService.selectUserList(sysUser);
        if (userList.isEmpty()) {
            return error("请输入正确的邮箱");
        }
        sysUser = userList.get(0);
        sysUser.setNickName(mailVo.nickname);
        // 设置权限
//        sysUser.setRoleIds(Constants.getRole(mailVo.getRole()));
        userService.updateUser(sysUser);
        userService.checkUserDataScope(sysUser.getUserId());
        userService.insertUserAuth(sysUser.getUserId(), Constants.getRole(mailVo.getRole()));

        // 刷新导航栏
        if ((long) sysUser.getUserId() == (long) SecurityUtils.getUserId()) {
            return success("chang myself");
        }
        return success("修改成功");
    }

    @PreAuthorize("@ss.hasAnyRoles('custom_admin,admin')")
    @GetMapping("/update_user_password")
    public synchronized AjaxResult updatePassword(UserPasswordVo vo) {
        if (!Helper.isValidPassword(vo.getPassword())) {
            return error("密码为8-16位,需包含数字和字母");
        }

        if (vo.getMail() == null || vo.getMail().isEmpty()) {
            return error("邮件为空");
        }

        SysUser sysUser = userService.selectUserByUserName(vo.getMail());
        if (sysUser == null) {
            return error("无效数据");
//            sysUser = new SysUser();
//            String username = franchiser.getPhone();
//            sysUser.setUserName(username);
//            sysUser.setNickName(username);
//            sysUser.setPassword(SecurityUtils.encryptPassword(vo.getPassword()));
//            boolean regFlag = userService.registerUser(sysUser);
//            if (!regFlag) {
//                return error("注册失败,请联系系统管理人员");
//            }
//            // 设置权限
////        userService.checkUserDataScope(sysUser.getUserId());
//            userService.insertUserAuth(sysUser.getUserId(), Constants.getRole(Constants.ROLE_SELLER));
//            return success();
        }
        sysUser.setPassword(SecurityUtils.encryptPassword(vo.getPassword()));
        sysUser.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(sysUser));
    }


    public boolean isRoleAdmin() {
        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
        for (SysRole r : userRoles) {
            if (r.getRoleId() == Constants.ROLE_ID_ADMIN) {
                return true;
            }
        }
        return false;
    }
}
